define(function(){
    var ec=require('echarts');
    require('echarts/chart/line');
    require('echarts/chart/bar');
    var zrUtil = require('zrender/tool/util');
    var zrnumber = require('echarts/util/number');


    var option_hour={
        title:{
           x:'center',
            y:'top'
        },
        grid:{
            x:'13%',
            y:'10%',
            x2:'0%'
        },
        tooltip : {
            trigger: 'axis'
            //formatter: '{b}min<br/>{a}:{c}'
        },
        calculable : true,
        xAxis : [
            {
                type : 'category',
                axisLabel:{
                    interval:6
                    //formatter: '{value}min'
                },
                data:[]
            }
        ],
        yAxis : [
            {
                type : 'value'
            }
        ],
        series : [
            {
                name:'',
                itemStyle:{
                    normal:{
                        color:'#C6E579'
                    }
                },
                type:'bar',
                stack:'group',
                data:[]
            }
        ]

    };
    var option_day = {
        title:{
           x:'center',
            y:'top'
        },
        grid:{
            x:'13%',
            y:'8%',
            x2:'0%'
        },
        tooltip : {
            trigger: 'axis',
            formatter: function(param){
                var result=param[0][1]+'点<br/>';
                result+=param[0][0]+' : '+zrnumber.addCommas(param[0][2])+'<br/>';
                result+=param[1][0]+' : '+zrnumber.addCommas(param[1][2])+'<br/>';
                if(param[0].data&&param[0].dataIndex-1>=0){
                    var lasthour= param[0].series.data[param[0].dataIndex-1];
                    var s=(((param[0].data/lasthour)-1)*100).toFixed(2);
                     result+='日环比 : ';
                    if(s>0){
                        result+='<span style="color: orangered">'+s+'%&#8593</span>';
                    }else{
                        result+='<span style="color: greenyellow">'+s+'%&#8595</span>';
                    }
                    result+='<br/>';
                }
                if(param[0].data&&param[1].data){
                    var s2=(((param[0].data/param[1].data)-1)*100).toFixed(2);
                    result+='日同比 : ';
                    if(s2>0){
                        result+='<span style="color: orangered">'+s2+'%&#8593</span>';
                    }else{
                        result+='<span style="color: greenyellow">'+s2+'%&#8595</span>';
                    }
                }
                return result;
            }
        },
        calculable : true,
        xAxis : [
            {
                type : 'category',
                data:function(){
                    var hour=[];
                    for(var i=0;i<=23;i++){
                        hour[i]=i;
                    }
                    return hour;
                }()
            }
        ],
        yAxis : [
            {
                type : 'value'
            }
        ],
        legend:{
            data:['今日数据','昨日数据'],
            x:'right'
        },
        series : [
            {
                name:'今日数据',
                type:'line',
                data:[]
            },
            {
                name:'昨日数据',
                type:'line',
                data:[]
            }
        ]
    };

    function RTChartHour(id,type){
        this.id=id;
        this.type=type;
        //this.mincache=[];
        this.option=zrUtil.clone(option_hour);
        this.myChart=ec.init(document.getElementById(id));
    }
    
            function getHoursKey(date){
            var key;
            if(date.getMinutes()<10){
                key=date.getHours()+':0'+date.getMinutes();
            }else{
                key=date.getHours()+':'+date.getMinutes();
            }
            return key;
        }

    RTChartHour.prototype.getSeriesData=function(data){
        if(!data)return [];
        //var i=-1;
        //var arr=[];
        //$.each(data,function(index,value){
        //        if(index%6==0){i++;arr[i]=0};
        //        arr[i]=Number((arr[i]+value.value).toFixed(2));
        //    }
        //);

        var da={};
        $.each(data,function(index,value){
            var date=new Date(value.time);
            var key=getHoursKey(date);
            if(da[key]){
                da[key]=Number((da[key]+value.value).toFixed(2));
            }else{
                da[key]=value.value;
            }
        });
        var x=[];
        var y=[];
        $.each(da,function(key,value){
            x.push(key);
            y.push(value);
        });
        if(x.length>60){
            var i= x.length-60;
            while(i--){
                x.shift();
                y.shift();
            }
        }
        return {'x':x,'y':y};
       // return arr;
    }

    RTChartHour.prototype.init=function(bussline,platform){
        var self=this;
        self.myChart.showLoading({
            text: '正在努力的读取数据中...'
        });
        $.ajax({
            url: '/dashboard/realtime/cpc/getHourData',
            type: 'POST',
            async: true,
            data:{"type":self.type,"bussline":bussline,"platform":platform},
            dataType: 'json',
            success:function(data){
                if(data.data&&data.data.length>0){
                    //self.data=data.data;
                    self.lasttime=data.data[data.data.length-1].time;
                    self.option.title.text=title[self.type];
                    self.option.series[0].name=title[self.type];
                    self.option.series[0].itemStyle.normal.color=colorlist[self.type];
                    var xy=self.getSeriesData(data.data);
                    self.option.xAxis[0].data=xy.x;
                    self.option.series[0].data=xy.y;
                    //self.option.series[0].data=self.getSeriesData(data.data);
                };
                self.myChart.setOption(self.option);
                self.myChart.hideLoading();

                clearInterval(timeTicket);
                var timeTicket = setInterval(function(){flush(self)}, 1*1000);
                function flush(obj){
                    $.ajax({
                        url: '/dashboard/realtime/cpc/getHourData',
                        type: 'POST',
                        async: false,
                        data:{"type":self.type,"bussline":bussline,"platform":platform,"time":obj.lasttime},
                        dataType: 'json',
                        success:function(data){
                            if(!data.data||data.data.length==0)return;
                            obj.lasttime=data.data[data.data.length-1].time;
                            //obj.counter+=data.data.length;
                            //缓存360个最新数据
                            $.each(data.data,function(index,value){
                               var date=new Date(value.time);
                               var key=getHoursKey(date);
                               var x=self.option.xAxis[0].data;
                                var y=self.option.series[0].data;
                               if(key==x[x.length-1]){
                                   y[y.length-1]=Number((y[y.length-1]+value.value).toFixed(2))
                                   self.myChart.setOption(self.option);
                               }else{
                                   x.shift();y.shift();
                                   x.push(key);y.push(value.value);
                                   self.myChart.addData([
                                       [
                                           0,        // 系列索引
                                           y[y.length-1], // 新增数据
                                           false,     // 新增数据是否从队列头部插入
                                           false,     // 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
                                           x[x.length-1]
                                       ]
                                   ]);
                               }
                               // if(self.data.length>=360)self.data.shift();
                                //self.data.push(value);
                                //if(self.mincache.length%6==0){
                                //    self.myChart.addData([
                                //        [
                                //            0,        // 系列索引
                                //            value.value, // 新增数据
                                //            false,     // 新增数据是否从队列头部插入
                                //            false     // 是否增加队列长度，false则自定删除原有数据，队头插入删队尾，队尾插入删队头
                                //        ]
                                //    ]);
                                //    self.mincache=[value];
                                //}else{
                                //    self.mincache.push(value);
                                //}
                            });

                            //if(self.mincache.length>1){
                            //    var add=0;
                            //    $.each(self.mincache,function(index,value){
                            //            add=Number((add+value.value).toFixed(2));
                            //});
                            //    var last=self.option.series[0].data.length-1;
                            //    self.option.series[0].data[last]=add;
                            //    self.myChart.setOption(self.option);
                            //}

                            //如果小于360个直接刷新
                            //if(self.data.length<360){
                            //    self.option.series[0].data=self.getSeriesData(self.data);
                            //    self.myChart.setOption(self.option);
                            //    return;
                            //}

                            ////大于6个时整体更新
                            //if(data.data.length>6){
                            //    self.option.series[0].data=self.getSeriesData();
                            //    self.myChart.setOption(self.option);
                            //}else{
                            //
                            //}
                            //console.log(data);
                        }
                    });
                }
            },
            timeout:5000,
            error : function() {
                self.myChart.hideLoading();
            }
        });
    }

    function RTChartDay(id,type){
        this.id=id;
        this.type=type;
        this.lasttime=0;
        this.option=zrUtil.clone(option_day);
        this.myChart=ec.init(document.getElementById(id));
    }

    RTChartDay.prototype.init=function(bussline,platform){
        var self=this;
        self.myChart.showLoading({
            text: '正在努力的读取数据中...'
        });
        function update(data){
            self.data=data.data;
            if(data.data&&data.data.length>0){
                //self.lasttime=data.data[data.data.length-1].time;
                var ss=[],ss2=[];
                $.each(data.data,function(index,value){
                    ss.push(value.value);
                });
                self.option.series[0].data=ss;
            }
            if(data.yesdata){
                $.each(data.yesdata,function(index,value){
                    ss2.push(value.value);
                });
                self.option.series[1].data=ss2;
            }
            self.myChart.setOption(self.option,true);
        }
        $.ajax({
            url: '/dashboard/realtime/cpc/getDayData',
            type: 'POST',
            async: true,
            data:{"type":self.type,"bussline":bussline,"platform":platform},
            dataType: 'json',
            success:function(data){
                self.option.title.text=title[self.type];
                update(data);
                self.myChart.hideLoading();
                clearInterval(timeTicket);
                var timeTicket = setInterval(function(){flush(self)}, 5*60*1000);
                function flush(obj){
                    $.ajax({
                        url: '/dashboard/realtime/cpc/getDayData',
                        type: 'POST',
                        async: true,
                        data:{"type":self.type,"bussline":bussline,"platform":platform,"time":obj.lasttime},
                        dataType: 'json',
                        success:function(data){
                            console.log('getDayData:');
                            console.log(data)
                            update(data);
                        }
                    });
                }
            },
            timeout:5000,
            error : function() {
                self.myChart.hideLoading();
            }
        });
    }

    function start(bussline,platform){
    	$('#cash').html(zrnumber.addCommas($('#cash').html()));
        $('#cost').html(zrnumber.addCommas($('#cost').html()));
        clearInterval(timeTicket);
        var timeTicket = setInterval(function(){flushCash()}, 3*1000);
        /**
         *
         */
        function flushCash(){
            $.ajax({
                url: '/dashboard/realtime/cpc/getCashCost',
                type: 'POST',
                async: true,
                data:{"bussline":bussline,"platform":platform},
                dataType: 'json',
                success:function(data){
                    $('#cash').html(zrnumber.addCommas(data.cash));
                    $('#cost').html(zrnumber.addCommas(data.cost));
                },
                timeout:5000
            });}

        var crt_cash_day = new RTChartDay('cash_day','click_cash');
        var crt_cash_hour =new RTChartHour('cash_hour','click_cash');
        crt_cash_day.init(bussline,platform);
        crt_cash_hour.init(bussline,platform);

        var crt_cost_day = new RTChartDay('cost_day','click_cost');
        var crt_cost_hour =new RTChartHour('cost_hour','click_cost');
        crt_cost_day.init(bussline,platform);
        crt_cost_hour.init(bussline,platform);

        var click_pv_day = new RTChartDay('click_pv_day','click_pv');
        var click_pv_hour =new RTChartHour('click_pv_hour','click_pv');
        click_pv_day.init(bussline,platform);
        click_pv_hour.init(bussline,platform);

        var disp_pv_day = new RTChartDay('disp_pv_day','disp_pv');
        var disp_pv_hour =new RTChartHour('disp_pv_hour','disp_pv');
        disp_pv_day.init(bussline,platform);
        disp_pv_hour.init(bussline,platform);

        var dispadnum_day = new RTChartDay('dispadnum_day','disp_adNum');
        var dispadnum_hour =new RTChartHour('dispadnum_hour','disp_adNum');
        dispadnum_day.init(bussline,platform);
        dispadnum_hour.init(bussline,platform);

        // var clickcustnum_day = new RTChartDay('clickcustnum_day','click_custNum');
        // var clickcustnum_hour =new RTChartHour('clickcustnum_hour','click_custNum');
        // clickcustnum_day.init(bussline,platform);
        // clickcustnum_hour.init(bussline,platform);

        var dispad_day = new RTChartDay('dispad_day','disp_ad');
        var dispad_hour =new RTChartHour('dispad_hour','disp_ad');
        dispad_day.init(bussline,platform);
        dispad_hour.init(bussline,platform);
    }

        var title={
        click_cash:' cash（现金）',
        click_cost:'cost（消费）',
        click_custNum:'cusCount（点击客户数）',
        click_pv:'click（点击）',
        disp_adNum:'disp（广告展现量）',
        disp_pv:'pv（列表页PV）',
        disp_ad:'adpv（广告PV)'
    }

    var colorlist={
        click_cash:'#C1232B',
        click_cost:'#B5C334',
        click_custNum:'#FCCE10',
        click_pv:'#9BCA63',
        disp_adNum:'#26C0C0',
        disp_pv:'#F0805A',
        disp_ad:'#F3A43B'
    }

    return {'start':start};
});